package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.Shelves;
import com.geek.factory.result.Result;
import com.geek.factory.service.IShelvesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 货柜管理控制器
 */
@RestController
@RequestMapping("/shelves")
@Api(tags = "后台系统的 - 货柜模块")
@Slf4j
@CrossOrigin
public class ShelvesController {

    @Autowired
    private IShelvesService shelvesService;

    /**
     * 生成货柜编码
     */
    private String generateShelfCodeInternal() {
        String prefix = "S";  // S = Shelf
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return prefix + dateStr + timeStr;
    }

    @ApiOperation("生成货柜编码")
    @GetMapping("/generate-code")
    public Result generateShelfCode() {
        try {
            String shelfCode = generateShelfCodeInternal();
            Map<String, String> result = new HashMap<>();
            result.put("shelfCode", shelfCode);
            return new Result(SuccessConstant.SUCCESS, "生成成功", result);
        } catch (Exception e) {
            log.error("生成货柜编码失败", e);
            return new Result(SuccessConstant.FAIL, "生成失败");
        }
    }

    @ApiOperation("通过ID查询货柜信息")
    @GetMapping("/{shelfId}")
    public Result findShelvesById(@ApiParam("货柜ID") @PathVariable("shelfId") Integer shelfId) {
        Shelves shelves = shelvesService.getById(shelfId);
        log.info("shelves: {}", shelves);
        if (shelves != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", shelves);
        }
        return new Result(SuccessConstant.FAIL, "货柜不存在");
    }

    // 新增货柜
    @ApiOperation("新增货柜")
    @PostMapping
    public Result addShelves(@RequestBody Shelves shelves) {
        // 如果没有设置货柜编码，自动生成
        if (shelves.getShelfCode() == null || shelves.getShelfCode().trim().isEmpty()) {
            shelves.setShelfCode(generateShelfCodeInternal());
        }

        // 设置默认值
        if (shelves.getStatus() == null) {
            shelves.setStatus(true); // 默认启用
        }
        if (shelves.getCreatedTime() == null) {
            shelves.setCreatedTime(LocalDateTime.now());
        }
        if (shelves.getCreatedBy() == null || shelves.getCreatedBy().trim().isEmpty()) {
            shelves.setCreatedBy("admin");
        }

        boolean isSuccess = shelvesService.save(shelves);
        log.info("新增货柜: {}, 结果: {}", shelves, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", shelves);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    // 根据ID删除货柜
    @ApiOperation("根据ID删除货柜")
    @DeleteMapping("/{shelfId}")
    public Result deleteShelves(@ApiParam("货柜ID") @PathVariable("shelfId") Integer shelfId) {
        boolean isSuccess = shelvesService.removeById(shelfId);
        log.info("删除货柜ID: {}, 结果: {}", shelfId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    // 修改货柜信息
    @ApiOperation("修改货柜信息")
    @PutMapping("/{shelfId}")
    public Result updateShelves(@ApiParam("货柜ID") @PathVariable("shelfId") Integer shelfId, @RequestBody Shelves shelves) {
        shelves.setShelfId(shelfId);
        boolean isSuccess = shelvesService.updateById(shelves);
        log.info("修改货柜: {}, 结果: {}", shelves, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", shelves);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("分页查询货柜列表")
    @GetMapping("/page")
    public Result getShelvesPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String shelfName,
            @RequestParam(required = false) String shelfCode,
            @RequestParam(required = false) Boolean status
    ) {
        LambdaQueryWrapper<Shelves> wrapper = new LambdaQueryWrapper<>();
        if (shelfName != null && !shelfName.trim().isEmpty()) {
            wrapper.like(Shelves::getShelfName, shelfName);
        }
        if (shelfCode != null && !shelfCode.trim().isEmpty()) {
            wrapper.like(Shelves::getShelfCode, shelfCode);
        }
        if (status != null) {
            wrapper.eq(Shelves::getStatus, status);
        }
        wrapper.orderByDesc(Shelves::getCreatedTime);

        Page<Shelves> page = shelvesService.page(new Page<>(current, size), wrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());
        data.put("pages", page.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("获取所有货柜列表")
    @GetMapping("/list")
    public Result getAllShelves() {
        LambdaQueryWrapper<Shelves> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Shelves::getStatus, true); // 只查询启用的货柜
        wrapper.orderByAsc(Shelves::getShelfName);
        List<Shelves> shelves = shelvesService.list(wrapper);
        return new Result(SuccessConstant.SUCCESS, "查询成功", shelves);
    }

    @ApiOperation("获取货柜统计数据")
    @GetMapping("/stats")
    public Result getShelfStats() {
        try {
            // 获取货柜数量
            long shelfCount = shelvesService.count();

            Map<String, Object> stats = new HashMap<>();
            stats.put("totalShelves", shelfCount);

            return new Result(SuccessConstant.SUCCESS, "查询成功", stats);
        } catch (Exception e) {
            log.error("获取货柜统计数据失败", e);
            return new Result(SuccessConstant.FAIL, "获取统计数据失败");
        }
    }
}